﻿using System;
using System.Text;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Threading;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;

namespace BaiTeacher
{
    /*需要Microsoft Huihui Desktop - Chinese (Simplified)的支持*/
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            syn = new SpeechSynthesizer();
            syn.Rate = -3;
            syn.Volume = 100;
            al = new ArrayList();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {

        }

        SpeechSynthesizer syn;
        string fName;
        ArrayList al;
        string filePath,fileName; //当前文件的路径 

        public int Delayed
        {
            get
            {
                return (int)nudSecond.Value * 1000;
            }
        }

        /// <summary>
        /// 读出某一个文本内容.
        /// </summary>
        /// <param name="voice"></param>
        void speak(string voice)
        {
            //syn.SelectVoice("Microsoft Huihui Desktop - Chinese (Simplified)");
            syn.SpeakAsync(voice);
        }

        /// <summary>
        /// 从指定的路径(Path)的文本文件中读取内容,并保存到arraylist中。
        /// </summary>
        /// <param name="path"></param>
        public void readFile(string path)
        {
            clbWord.Items.Clear();
            StreamReader sr = new StreamReader(path, Encoding.Default);
            String line;
            int _charnum = 0;
            while ((line = sr.ReadLine()) != null)
            {
                string[] split = line.Split(new Char[] { '\t' });
                foreach (string s in split)
                {
                    if (s.Trim() != "")
                    {
                        _charnum = CharNum(s.Trim(), "|");
                        if (_charnum == 0)
                        {
                            al.Add(s+"||"+ nudSecond.Value.ToString());
                        }
                        else if (_charnum == 1)
                        {
                            al.Add(s + "|" + nudSecond.Value.ToString());
                        }else
                        {
                            al.Add(s);
                        }
                    }
                        
                }
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if ((fName == "") || (fName == null))
            {
                return;
            }

            clbWord.Items.Clear();
            al.Clear();//清理al中的所有的内容。
            readFile(fName);//将文件中的内容填入到al中。
            filePath = Path.GetDirectoryName(fName); //得到当前文件的路径
            fileName = Path.GetFileNameWithoutExtension(fName); //得到当前文件的
            speak("大家好,我是白老师,现在我们开始听写练习吧.");
            Thread.Sleep(12000);
            pb.Maximum = al.Count;
            pb.Minimum = 1;
            for (int i = 0; i < al.Count; i++)
            {
                //读出一行内容,并分解出三部分内容：1、要读的内容，2、答案 3、暂停的长度(没有设定就为默认值)
                string str_one= al[i].ToString(); //每一行数据
                string[] _voice = SplitX(str_one);
                string voice = _voice[0];
                string answer = _voice[1];
                int Delayed1 = int.Parse(_voice[2].ToString())*1000;
                clbWord.Items.Insert(0, voice);
                speak(voice);
                pb.Value = i+1;

                //Thread.Sleep(Delayed);
                //设置暂停长度
                if(i != al.Count-1)
                Thread.CurrentThread.Join(Delayed1);
            }
        }

        /// <summary>
        /// 分解字符串中的内容  史记的作者是谁?|司马迁|10
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private String[] SplitX(string str)
        {
            String[] tmpstr = str.Split(new[] { "|" }, StringSplitOptions.None);
             if (tmpstr.Length == 1)
            {
                tmpstr[1] = "";
                tmpstr[2] = Delayed.ToString();
            } else if (tmpstr.Length == 2)
            {
                tmpstr[2] = Delayed.ToString();
            }

            return tmpstr;
        }

        private void btnFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
            openFileDialog.Filter = "文本文件|*.txt";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                fName = openFileDialog.FileName;
            }
            tbFile.Text = fName;
        }


        //保存待处理的项
        private void save_Click(object sender, EventArgs e)
        {
            string aFileName = filePath +"\\"+ DateTime.Now.ToString("yyyyMMddHHmmssms") + ".txt";
            //StreamWriter sr = File.CreateText(aFileName);
            string strCollected = string.Empty;
            //for (int i = 0; i < clbWord.CheckedItems.Count; i++)
            //{
            //    if (clbWord.GetItemChecked(i))
            //    {
            //        strCollected = clbWord.GetItemText(clbWord.Items[i]);
            //        sr.WriteLine(strCollected);
            //    }
            //}
            //sr.Close();

            using (FileStream fs = new FileStream(aFileName, FileMode.Append, FileAccess.Write))
            {
                fs.Lock(0, fs.Length);
                StreamWriter sw = new StreamWriter(fs);
                for (int i = 0; i < clbWord.CheckedItems.Count; i++)
                {
                    strCollected = clbWord.CheckedItems[i].ToString();
                    //strCollected = clbWord.GetItemText(clbWord.Items[i]);
                    sw.WriteLine(strCollected);

                    //if (clbWord.GetItemChecked(i))
                    //{
                    //    strCollected = clbWord.CheckedItems[i].ToString();
                    //    //strCollected = clbWord.GetItemText(clbWord.Items[i]);
                    //    sw.WriteLine(strCollected);
                    //}
                }
                fs.Unlock(0, fs.Length);//一定要用在Flush()方法以前，否则抛出异常。
                sw.Flush();
            }

        }

        //统计字符串中某个字符的个数
        private int CharNum(string str, string subString)
        {
            if (str.Contains(subString))
            {
                string strReplaced = str.Replace(subString, "");
                return (str.Length - strReplaced.Length) / subString.Length;
            }
            return 0;

        }

    }
}
